package mysql

import (
	"context"
	"data-transfer/domain"
	"data-transfer/global"
	"data-transfer/transfer"
	"github.com/shopspring/decimal"
	"go.uber.org/zap"
)

//GetAllTestData 取得所有测试数据
func (mdb *db) GetAllTestData() ([]*domain.TEST_TARGET, error) {
	var datas []*domain.TEST
	err := mdb.db.NewSession().Where("ID > 0").Find(&datas)
	if err != nil {
		global.LOG.Error("获取测试数据出错:", zap.Any("err", err))
		return nil, err
	}

	var results []*domain.TEST_TARGET
	for _, o := range datas {
		r := new(domain.TEST_TARGET)
		r.Id = o.Id
		r.Value = o.Value
		results = append(results, r)
	}
	return results, err
}

//GetAllTqSkBasicInfo 取得所有股票基本信息
func (mdb *db) GetAllTqSkBasicInfo(ctx context.Context) ([]*domain.TQ_SK_BASICINFO, error) {
	var result []*domain.TQ_SK_BASICINFO
	// 只查询上市企业且不是优先股的
	err := mdb.db.NewSession().Where("ISVALID = ? AND LISTSTATUS = ? AND SETYPE != ?", 1, transfer.LISTSTATUS_1, transfer.SETYPE_109).Find(&result)
	return result, err
}

//GetAllCashFlowSq 根据股票信息，获取所有企业的单季度现金流
func (mdb *db) GetAllCashFlowSq(ctx context.Context, basicInfos []*domain.TQ_SK_BASICINFO) ([]*domain.CASH_FLOW_SQ, error) {
	var rows []*domain.CASH_FLOW_SQ

	for _, o := range basicInfos {
		var tempRows []*domain.CASH_FLOW_SQ //每一个compCode对应一个结果集

		symbol := o.Symbol //证券代码
		compCode := o.Compcode
		exchange := o.Exchange

		cashFlowsSq, err := mdb.GetTqFinPrgCfsqSubjectsByCompCode(ctx, compCode)
		if err != nil {
			global.LOG.Error("获取单季衍生现金科目(产品表）(TQ_FIN_PRGCFSQSUBJECTS) 数据出错:", zap.Any("err", err))
			return nil, err
		}

		for _, v := range cashFlowsSq {
			r := new(domain.CASH_FLOW_SQ)
			r.Symbol = symbol
			r.Exchange = transfer.TransferExchane(exchange) //市场代码
			r.Reportyear = v.Reportyear                     //会计年度
			r.Reportdatetype = v.Reportdatetype             //报告期类型
			r.Compcode = v.Compcode                         //机构代码
			r.Bizcashinfl = v.Bizcashinflopi                //经营活动现金流入小计
			r.Bizcashoutf = v.Bizcashoutfopo                //经营活动现金流出小计
			r.Mananetr = v.Mananetr                         //经营现金流量净额
			r.Invcashinfl = v.Invcashinflinvi               //投资活动现金流入小计
			r.Invcashoutf = v.Invcashoutfinvo               //投资活动现金流出小计
			r.Invnetcashflow = v.Invnetcashflow             //投资现金流量净额
			r.Fincashinfl = v.Fincashinflfini               //筹资活动现金流入小计
			r.Fincashoutf = v.Fincashoutffino               //筹资活动现金流出小计
			r.Finnetcflow = v.Finnetcflow                   //筹资现金流量净额
			r.Cashnetr = v.Cashnetr                         //现金及现金等价物净增加额
			tempRows = append(tempRows, r)
		}

		//累加每一个compCode的结果集
		rows = append(rows, tempRows...)
	}

	return rows, nil
}

//GetAllCashFlow 根据股票信息，获取所有企业的现金流
func (mdb *db) GetAllCashFlow(ctx context.Context, basicInfos []*domain.TQ_SK_BASICINFO) ([]*domain.CASH_FLOW, error) {

	var rows []*domain.CASH_FLOW

	for _, o := range basicInfos {

		var tempRows []*domain.CASH_FLOW //每一个compCode对应一个结果集

		symbol := o.Symbol //证券代码
		compCode := o.Compcode
		exchange := o.Exchange

		cashFlows, err := mdb.GetTqFinPrgCfStatementNewByCompCode(ctx, compCode)
		if err != nil {
			global.LOG.Error("获取 一般企业现金流量表(新准则产品表)(TQ_FIN_PRGCFSTATEMENTNEW) 数据出错", zap.Any("err", err))
			return nil, err
		}

		for _, v := range cashFlows {
			r := new(domain.CASH_FLOW)
			r.Symbol = symbol
			r.Exchange = transfer.TransferExchane(exchange) //市场代码
			r.Reportyear = v.Reportyear                     //会计年度
			r.Reportdatetype = v.Reportdatetype             //报告期类型
			r.Compcode = v.Compcode                         //机构代码
			r.Bizcashinfl = v.Bizcashinfl                   //经营活动现金流入小计
			r.Bizcashoutf = v.Bizcashoutf                   //经营活动现金流出小计
			r.Mananetr = v.Mananetr                         //经营现金流量净额
			r.Invcashinfl = v.Invcashinfl                   //投资活动现金流入小计
			r.Invcashoutf = v.Invcashoutf                   //投资活动现金流出小计
			r.Invnetcashflow = v.Invnetcashflow             //投资现金流量净额
			r.Fincashinfl = v.Fincashinfl                   //筹资活动现金流入小计
			r.Fincashoutf = v.Fincashoutf                   //筹资活动现金流出小计
			r.Finnetcflow = v.Finnetcflow                   //筹资现金流量净额
			r.Cashnetr = v.Cashnetr                         //现金及现金等价物净增加额
			tempRows = append(tempRows, r)
		}

		//累加每一个compCode的结果集
		rows = append(rows, tempRows...)
	}

	return rows, nil
}

//GetAllIncomeStatementSq 根据股票信息，获取所有企业单季度利润信息
func (mdb *db) GetAllIncomeStatementSq(ctx context.Context, basicInfos []*domain.TQ_SK_BASICINFO) ([]*domain.INCOME_STATEMENT_SQ, error) {
	var rows []*domain.INCOME_STATEMENT_SQ

	for _, o := range basicInfos {
		var tempRows []*domain.INCOME_STATEMENT_SQ //每一个compCode对应一个结果集

		symbol := o.Symbol //证券代码
		compCode := o.Compcode
		exchange := o.Exchange

		subjects, err := mdb.GetTqFinPrgPasqSubjectsByCompCode(ctx, compCode)
		if err != nil {
			global.LOG.Error("获取 单季衍生利润科目(产品表）(TQ_FIN_PRGPASQSUBJECTS) 数据出错", zap.Any("err", err))
			return nil, err
		}

		for _, v := range subjects {
			r := new(domain.INCOME_STATEMENT_SQ)

			r.Symbol = symbol
			r.Exchange = transfer.TransferExchane(exchange) //市场代码
			r.Reportyear = v.Reportyear                     //会计年度
			r.Reportdatetype = v.Reportdatetype             //报告期类型
			r.Compcode = v.Compcode                         //机构代码
			r.Biztotinco = v.Bizinco                        // 营业收入
			r.Biztotcost = v.Bizcost                        //营业成本
			r.Manaexpe = v.Mgtexpe                          //管理费用
			r.Salesexpe = v.Opexpe                          //营业费用
			r.Finexpe = v.Finlexpe                          //财务费用
			r.Perprofit = v.Opprofit                        //营业利润
			r.Inveinco = v.Inveinco                         // 投资收益
			//r.Nonoreve = v.Nonbizinco                     //营业外收支净额
			r.Nonoreve = v.Nnonopi         //营业外收支净额
			r.Nonoexpe = v.Nonbizcost      //设置为 营业外收支净额
			r.Totprofit = v.Totprofit      //利润总额
			r.Netprofit = v.Netprofitconms //净利润

			tempRows = append(tempRows, r)

		}
		//累加每一个compCode的结果集
		rows = append(rows, tempRows...)

	}

	return rows, nil
}

//GetAllIncomeStatement 根据股票信息，获取所有企业利润信息
func (mdb *db) GetAllIncomeStatement(ctx context.Context, basicInfos []*domain.TQ_SK_BASICINFO) ([]*domain.INCOME_STATEMENT, error) {

	var rows []*domain.INCOME_STATEMENT

	for _, o := range basicInfos {

		var tempRows []*domain.INCOME_STATEMENT //每一个compCode对应一个结果集

		symbol := o.Symbol //证券代码
		compCode := o.Compcode
		exchange := o.Exchange

		isBank := false
		//根据compCode判断企业性质
		compInfos, _ := mdb.GetTqCompInfoByCompCode(ctx, compCode)
		if len(compInfos) > 0 {
			compInfo := compInfos[0]
			if compInfo.Comptype1 == transfer.TQCOMPINFO_BDFI || compInfo.Comptype1 == transfer.TQCOMPINFO_BNDFI { //银行
				isBank = true
				//global.LOG.Info("企业性质为银行:", zap.String("compcode", compCode), zap.String("comptype1", compInfo.Comptype1))

			}
		}

		incomes, err := mdb.GetTqFinPrgIncStatementNewByCompCode(ctx, compCode)
		if err != nil {
			global.LOG.Error("获取 一般企业利润表(新准则产品表)(TQ_FIN_PRGINCSTATEMENTNEW) 数据出错", zap.Any("err", err))
			return nil, err
		}

		for _, v := range incomes {
			r := new(domain.INCOME_STATEMENT)
			r.Symbol = symbol
			r.Exchange = transfer.TransferExchane(exchange) //市场代码
			r.Reportyear = v.Reportyear                     //会计年度
			r.Reportdatetype = v.Reportdatetype             //报告期类型
			r.Compcode = v.Compcode                         //机构代码
			//r.Biztotinco = v.Biztotinco                     // 营业收入
			r.Biztotinco = v.Bizinco // 营业收入
			//r.Biztotcost = v.Biztotcost                     //营业成本
			r.Biztotcost = v.Bizcost //营业成本

			//如果是银行，查询银行利润表，取得相应日期和类型的数据
			if isBank {
				//global.LOG.Info("查询银行利润表查询条件:", zap.String("compcode", compCode), zap.String("Enddate", v.Enddate), zap.String("Reportyear", v.Reportyear), zap.String("Reportdatetype", v.Reportdatetype))
				binc, eb := mdb.GetTqFinPrgbincstatementnewByBizKey(ctx, compCode, v.Enddate, v.Reportyear, v.Reportdatetype)
				if eb != nil {
					global.LOG.Error("获取 银行利润表(新准则产品表) 数据出错", zap.Any("err", eb))
				}
				if binc != nil {
					//银行 三费合一  业务及管理费用
					expen := binc.Bizadminexpen
					r.Manaexpe = expen  //管理费用
					r.Salesexpe = expen //营业费用
					r.Finexpe = expen   //财务费用
				}
			} else {
				r.Manaexpe = v.Manaexpe   //管理费用
				r.Salesexpe = v.Salesexpe //营业费用
				r.Finexpe = v.Finexpe     //财务费用
			}

			r.Perprofit = v.Perprofit //营业利润
			r.Inveinco = v.Inveinco   // 投资收益
			r.Nonoreve = v.Nonoreve   //营业外收入净额
			r.Nonoexpe = v.Nonoexpe   //营业外支出净额
			//设置营业外收支净额
			nonoreveDec, _ := decimal.NewFromString(v.Nonoreve)
			nonoexpeDec, _ := decimal.NewFromString(v.Nonoexpe)
			nnoiDec := nonoreveDec.Sub(nonoexpeDec)
			r.Nonoreve = nnoiDec.String() //营业外收支净额

			r.Totprofit = v.Totprofit //利润总额
			r.Netprofit = v.Netprofit //净利润

			tempRows = append(tempRows, r)
		}

		//累加每一个compCode的结果集
		rows = append(rows, tempRows...)
	}

	return rows, nil
}

//GetAllTqFinPrgBalSheetNew 获取一般企业资产负债信息
func (mdb *db) GetAllTqFinPrgBalSheetNew(ctx context.Context, basicInfos []*domain.TQ_SK_BASICINFO) ([]*domain.BALANCE_SHEET, error) {

	var rows []*domain.BALANCE_SHEET

	for _, o := range basicInfos {

		var tempRows []*domain.BALANCE_SHEET //每一个compCode对应一个结果集

		symbol := o.Symbol //证券代码
		compCode := o.Compcode
		exchange := o.Exchange

		sheets, err := mdb.GetTqFinPrgBalSheetNewByCompCode(ctx, compCode)
		if err != nil {
			global.LOG.Error("获取 一般企业资产负债表(新准则产品表)(TQ_FIN_PRGBALSHEETNEW) 数据出错", zap.Any("err", err))
			return nil, err
		}

		for _, v := range sheets {
			r := new(domain.BALANCE_SHEET)
			r.Symbol = symbol
			r.Exchange = transfer.TransferExchane(exchange) //市场代码

			r.Reportyear = v.Reportyear           //会计年度
			r.Reportdatetype = v.Reportdatetype   //报告期类型
			r.Compcode = v.Compcode               //机构代码
			r.Totcurrasset = v.Totcurrasset       //流动资产
			r.Curfds = v.Curfds                   //货币资金
			r.Tradfinasset = v.Tradfinasset       //交易性金融资产
			r.Inve = v.Inve                       //存货
			r.Accorece = v.Accorece               //应收账款
			r.Otherrecetot = v.Otherrecetot       //其他应收款
			r.Totalnoncassets = v.Totalnoncassets //非流动资产合计
			r.Fixedassenet = v.Fixedassenet       //固定资产净额
			r.Avaisellasse = v.Avaisellasse       //可供出售金融资产
			r.Intaasset = v.Intaasset             //无形资产
			r.Goodwill = v.Goodwill               //商誉
			r.Totasset = v.Totasset               //总资产
			r.Totalcurrliab = v.Totalcurrliab     //流动负债合计
			r.Advapaym = v.Advapaym               //预收账款
			r.Accopaya = v.Accopaya               //应付账款
			r.Totalnoncliab = v.Totalnoncliab     //长期负债
			r.Totliab = v.Totliab                 //总负债
			r.Paresharrigh = v.Paresharrigh       //股东权益
			r.Capisurp = v.Capisurp               //资产公积金
			r.Shorttermborr = v.Shorttermborr     //短期借款

			tempRows = append(tempRows, r)
		}

		//累加每一个compCode的结果集
		rows = append(rows, tempRows...)
	}

	return rows, nil
}

//GetAllKeyIndicatorInfoSq 根据股票信息，取得所有财务指标数据(单季度)
func (mdb *db) GetAllKeyIndicatorInfoSq(ctx context.Context, basicInfos []*domain.TQ_SK_BASICINFO) ([]*domain.KEY_INDICATOR_SQ, error) {
	var rows []*domain.KEY_INDICATOR_SQ

	for _, o := range basicInfos {
		var tempRows []*domain.KEY_INDICATOR_SQ //每一个compCode对应一个结果集

		symbol := o.Symbol //证券代码
		compCode := o.Compcode
		exchange := o.Exchange

		// 1. 根据compCode 查询 单季衍生指标（产品表）(TQ_FIN_PROQINDIC)
		proQinDics, err := mdb.GetTqFinProQinDicByCompCode(ctx, compCode)
		if err != nil {
			global.LOG.Error("获取 TQ_FIN_PROQINDIC 单季衍生指标（产品表）数据出错", zap.Any("err", err))
			return nil, err
		}

		//取得基本每股收益
		subjects, err := mdb.GetTqFinPrgPasqSubjectsByCompCode(ctx, compCode)
		if err != nil {
			global.LOG.Error("获取 TQ_FIN_PRGPASQSUBJECTS 单季衍生利润科目(产品表）", zap.Any("err", err))
			return nil, err
		}

		//设置基本每股收益
		setIndicatorSqEpsBasic(proQinDics, subjects)

		// 设置财务数据-主要指标-单季度
		for _, v := range proQinDics {
			r := new(domain.KEY_INDICATOR_SQ)
			r.Symbol = symbol
			r.Exchange = transfer.TransferExchane(exchange) //市场代码
			r.Reportyear = v.Reportyear                     //会计年度
			r.Reportdatetype = v.Reportdatetype             //报告期类型
			r.Compcode = v.Compcode                         //机构代码
			r.Epsbasic = v.Basiceps                         //（一）基本每股收益 厂商2022年5月份开始处理
			r.Roediluted = v.Roediluted                     //净资产收益率_摊薄
			r.Opncfps = v.Opncfps                           //每股经营活动产生的现金流量净额
			r.Snpmarginconms = v.Sgpmargin                  // 销售毛利率
			r.Opprort = v.Opprort                           // 营业利润率
			r.Roediluted = v.Roediluted                     //摊薄净资产收益率

			tempRows = append(tempRows, r)
		}

		//累加
		rows = append(rows, tempRows...)
	}

	return rows, nil
}

func setIndicatorSqEpsBasic(indics []*domain.TQ_FIN_PROQINDIC, subjects []*domain.TQ_FIN_PRGPASQSUBJECTS) {
	for _, i := range indics {
		for _, s := range subjects {
			if i.Compcode == s.Compcode && i.Enddate == s.Enddate && i.Reportyear == s.Reportyear && i.Reporttype == s.Reporttype {
				//基本每股收益
				i.Basiceps = s.Basiceps
			}

		}
	}
}

//GetAllKeyIndicatorInfo 根据股票信息，取得所有财务指标数据
func (mdb *db) GetAllKeyIndicatorInfo(ctx context.Context, basicInfos []*domain.TQ_SK_BASICINFO) ([]*domain.KEY_INDICATOR, error) {

	var rows []*domain.KEY_INDICATOR

	for _, o := range basicInfos {

		var tempRows []*domain.KEY_INDICATOR //每一个compCode对应一个结果集

		symbol := o.Symbol //证券代码
		compCode := o.Compcode
		exchange := o.Exchange

		// 1. 根据compCode 查询 主要财务指标(产品表）(TQ_FIN_PRGFINMAININDEX)
		// 以此表的会计年度和报告期类型为基准表来设置其他数据
		mainIndexs, err := mdb.GetTqFinPrgFinMainIndexByCompCode(ctx, compCode)
		if err != nil {
			global.LOG.Error("获取 TQ_FIN_PRGFINMAININDEX 主要财务指标(产品表）数据出错", zap.Any("err", err))
			return nil, err
		}

		//根据compCode 设置主要财务指标数据
		for _, v := range mainIndexs {
			r := new(domain.KEY_INDICATOR)
			r.Symbol = symbol
			r.Exchange = transfer.TransferExchane(exchange) //市场代码
			r.Reportyear = v.Reportyear                     //会计年度
			r.Reportdatetype = v.Reportdatetype             //报告期类型
			r.Compcode = v.Compcode                         //机构代码
			r.Epsbasic = v.Epsbasic                         //（一）基本每股收益
			//	r.Roediluted = v.Roediluted                     //净资产收益率_摊薄
			//	r.Roeweighted = v.Roeweighted                   //净资产收益率_加权
			//	r.Naps = v.Naps                                 //每股净资产
			//	r.Opncfps = v.Opncfps                           //每股经营活动产生的现金流量净额
			r.Enddate = v.Enddate

			tempRows = append(tempRows, r)
		}
		//global.LOG.Info("--------------------------------------------")
		//global.LOG.Info("mainIndex.length", zap.Int("slice.length", len(tempRows)))

		//2. 根据compCode 查询衍生财务指标(产品表)
		indicDatas, err := mdb.GetTqFinPrgIndicDataByCompCode(ctx, compCode)
		if err != nil {
			global.LOG.Error("获取 衍生财务指标(产品表)_V3(TQ_FIN_PRGINDICDATA) 数据出错", zap.Any("err", err))
			return nil, err
		}

		//global.LOG.Info("indicDatas.length", zap.Int("slice.length", len(indicDatas)))
		//global.LOG.Info("--------------------------------------------")

		//3. 设置同一个compCode下的相同 报告期年度 和 报告期类型 的 衍生财务指标数据
		tempRows = setIndicData(tempRows, indicDatas)

		//4.根据compCode 查询 衍生财务指标副表(产品表)数据
		indicDatasSubs, err := mdb.GetTqFinPrgIndicDataSubByCompCode(ctx, compCode)
		if err != nil {
			global.LOG.Error("获取 衍生财务指标副表(产品表)_V3(TQ_FIN_PRGINDICDATASUB) 数据出错", zap.Any("err", err))
			return nil, err
		}

		//5.设置同一个compCode下的相同 报告期年度 和 报告期类型 的 衍生财务指标副表数据
		tempRows = setIndicDatasSubs(tempRows, indicDatasSubs)

		//累加
		rows = append(rows, tempRows...)
	}

	return rows, nil
}

//GetTqFinPrgBalSheetNewByCompCode 取得财务数据-资产负债表
func (mdb *db) GetTqFinPrgBalSheetNewByCompCode(ctx context.Context, compCode string) ([]*domain.TQ_FIN_PRGBALSHEETNEW, error) {
	var results []*domain.TQ_FIN_PRGBALSHEETNEW
	err := mdb.db.NewSession().Where("ISVALID=? and REPORTTYPE = ? and COMPCODE = ?", 1, transfer.REPORTTYPE_1, compCode).Asc("REPORTYEAR").Find(&results)
	return results, err
}

//GetTqFinPrgFinMainIndexByCompCode  根据 compCode 取得 主要财务指标(产品表） 信息
func (mdb *db) GetTqFinPrgFinMainIndexByCompCode(ctx context.Context, compCode string) ([]*domain.TQ_FIN_PRGFINMAININDEX, error) {
	var results []*domain.TQ_FIN_PRGFINMAININDEX
	err := mdb.db.NewSession().Where("ISVALID=? and REPORTTYPE = ? and COMPCODE = ?", 1, transfer.REPORTTYPE_1, compCode).Asc("REPORTYEAR").Find(&results)
	return results, err
}

//GetTqFinProQinDicByCompCode 财务数据-主要指标-单季度
func (mdb *db) GetTqFinProQinDicByCompCode(ctx context.Context, compCode string) ([]*domain.TQ_FIN_PROQINDIC, error) {
	var results []*domain.TQ_FIN_PROQINDIC
	err := mdb.db.NewSession().Where("ISVALID=? and (REPORTTYPE = ? or REPORTTYPE = ?) and  COMPCODE = ? ", 1, transfer.REPORTTYPE_1, transfer.REPORTTYPE_c3, compCode).Asc("REPORTYEAR").Find(&results)
	return results, err
}

// GetTqFinPrgIndicDataByCompCode 据 companyCode 取得 衍生财务指标(产品表)信息
func (mdb *db) GetTqFinPrgIndicDataByCompCode(ctx context.Context, compCode string) ([]*domain.TQ_FIN_PRGINDICDATA, error) {
	var results []*domain.TQ_FIN_PRGINDICDATA
	err := mdb.db.NewSession().Where("ISVALID=? and (REPORTTYPE = ? or REPORTTYPE = ?) and  COMPCODE = ? ", 1, transfer.REPORTTYPE_1, transfer.REPORTTYPE_c3, compCode).Asc("REPORTYEAR").Find(&results)
	return results, err
}

//GetTqFinPrgIndicDataSubByCompCode 财务数据-主要指标：根据 compCode 取得 衍生财务指标副表(产品表) 数据
func (mdb *db) GetTqFinPrgIndicDataSubByCompCode(ctx context.Context, compCode string) ([]*domain.TQ_FIN_PRGINDICDATASUB, error) {
	var results []*domain.TQ_FIN_PRGINDICDATASUB
	err := mdb.db.NewSession().Where("ISVALID=? and REPORTTYPE = ? and COMPCODE = ?", 1, transfer.REPORTTYPE_c3, compCode).Asc("REPORTYEAR").Find(&results)
	return results, err
}

// GetTqFinPrgIncStatementNewByCompCode 取得财务数据： 根据 compCode 取得  一般企业利润表(新准则产品表)
func (mdb *db) GetTqFinPrgIncStatementNewByCompCode(ctx context.Context, compCode string) ([]*domain.TQ_FIN_PRGINCSTATEMENTNEW, error) {
	var results []*domain.TQ_FIN_PRGINCSTATEMENTNEW
	err := mdb.db.NewSession().Where("ISVALID=? and REPORTTYPE = ? and COMPCODE = ?", 1, transfer.REPORTTYPE_1, compCode).Asc("REPORTYEAR").Find(&results)
	return results, err
}

//GetTqFinPrgPasqSubjectsByCompCode 取得财务数据： 根据 compCode 取得  单季衍生利润科目(产品表）
func (mdb *db) GetTqFinPrgPasqSubjectsByCompCode(ctx context.Context, compCode string) ([]*domain.TQ_FIN_PRGPASQSUBJECTS, error) {
	var results []*domain.TQ_FIN_PRGPASQSUBJECTS
	err := mdb.db.NewSession().Where("ISVALID=? and (REPORTTYPE = ? or REPORTTYPE = ?) and  COMPCODE = ? ", 1, transfer.REPORTTYPE_1, transfer.REPORTTYPE_c3, compCode).Asc("REPORTYEAR").Find(&results)
	return results, err
}

//GetTqFinPrgCfStatementNewByCompCode 取得财务数据：根据 compCode 取得 一般企业现金流量表(新准则产品表)
func (mdb *db) GetTqFinPrgCfStatementNewByCompCode(ctx context.Context, compCode string) ([]*domain.TQ_FIN_PRGCFSTATEMENTNEW, error) {
	var results []*domain.TQ_FIN_PRGCFSTATEMENTNEW
	err := mdb.db.NewSession().Where("ISVALID=? and REPORTTYPE = ? and COMPCODE = ?", 1, transfer.REPORTTYPE_1, compCode).Asc("REPORTYEAR").Find(&results)
	return results, err
}

//GetTqFinPrgCfsqSubjectsByCompCode 取得财务数据：根据 compCode 取得 一般企业现金流-单季度量表(新准则产品表)
func (mdb *db) GetTqFinPrgCfsqSubjectsByCompCode(ctx context.Context, compCode string) ([]*domain.TQ_FIN_PRGCFSQSUBJECTS, error) {
	var results []*domain.TQ_FIN_PRGCFSQSUBJECTS
	err := mdb.db.NewSession().Where("ISVALID=? and (REPORTTYPE = ? or REPORTTYPE = ?) and  COMPCODE = ? ", 1, transfer.REPORTTYPE_1, transfer.REPORTTYPE_c3, compCode).Asc("REPORTYEAR").Find(&results)
	return results, err
}

// GetTqFinPrgbincstatementnewByBizKey 取得银行利润信息
func (mdb *db) GetTqFinPrgbincstatementnewByBizKey(ctx context.Context, compCode string, endDate string, reportYear string, reportDateType string) (*domain.TQ_FIN_PRGBINCSTATEMENTNEW, error) {
	var results []*domain.TQ_FIN_PRGBINCSTATEMENTNEW
	err := mdb.db.NewSession().Where("ISVALID=? and REPORTTYPE = ?  and  COMPCODE = ? and ENDDATE = ? and REPORTYEAR = ? and REPORTDATETYPE = ?", 1, transfer.REPORTTYPE_1, compCode, endDate, reportYear, reportDateType).Desc("REPORTYEAR").Find(&results)
	if err != nil {
		return nil, err
	}
	if len(results) > 0 {
		return results[0], nil
	}
	return nil, nil
}

// setIndicDatasSubs 设置衍生财务指标副表数据
func setIndicDatasSubs(s []*domain.KEY_INDICATOR, t []*domain.TQ_FIN_PRGINDICDATASUB) []*domain.KEY_INDICATOR {
	if len(s) == 0 || len(t) == 0 {
		return s
	}
	//	if len(s) == len(t) {
	for _, o := range t {

		for _, v := range s {
			if v.Compcode == v.Compcode && v.Enddate == o.Enddate && v.Reportyear == o.Reportyear && v.Reportdatetype == o.Reportdatetype {
				v.Profitratio = o.Profitratio //净利润率(%)
			}
		}

	}
	//} else {
	//	global.LOG.Info("......数据有异常，TQ_FIN_PRGINDICDATASUB 表数量未匹配......", zap.Int("KeyIndicatorNum", len(s)), zap.Int("TqFinPrgIndicDataSubNum", len(t)))
	//
	//}
	return s
}

// setIndicData 设置衍生财务指标数据
// 默认为s和t的长度是相等的
func setIndicData(s []*domain.KEY_INDICATOR, t []*domain.TQ_FIN_PRGINDICDATA) []*domain.KEY_INDICATOR {
	if len(s) == 0 || len(t) == 0 {
		return s
	}

	//	if len(s) == len(t) {
	for _, o := range t {
		for _, v := range s {
			if v.Compcode == o.Compcode && v.Enddate == o.Enddate && v.Reportyear == o.Reportyear && v.Reportdatetype == o.Reportdatetype {
				v.Naps = o.Naps       //每股净资产
				v.Opncfps = o.Opncfps //每股经营性现金流量
				v.Upps = o.Upps       //每股未分配利润
				v.Crps = o.Crps       //每股资本公积金
				//v.Snpmarginconms = o.Snpmarginconms //销售净利率(含少数股权权益)
				v.Snpmarginconms = o.Sgpmargin //销售毛利率
				v.Roeweighted = o.Roeavg       //加权净资产收益率
				v.Roediluted = o.Roediluted    //摊薄净资产收益率
				v.Opprort = o.Opprort          //营业利润率
				v.Currentrt = o.Currentrt      //流动比率
				v.Quickrt = o.Quickrt          //速动比率
			}
		}

	}

	//} else {
	//	global.LOG.Info("......数据有异常，TQ_FIN_PRGINDICDATA 表数量未匹配......", zap.Int("KeyIndicatorNum", len(s)), zap.Int("TqFinPrgIndicData", len(t)))
	//
	//}

	return s
}
